package client;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.security.MessageDigest;

import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.THttpClient;

import com.evernote.edam.notestore.NoteStore;
import com.evernote.edam.type.Data;
import com.evernote.edam.type.Note;
import com.evernote.edam.type.NoteAttributes;
import com.evernote.edam.type.Notebook;
import com.evernote.edam.type.Resource;
import com.evernote.edam.type.ResourceAttributes;
import com.evernote.edam.userstore.Constants;
import com.evernote.edam.userstore.UserStore;

public class Testando {
	private static final String authToken = "";
	private static final String evernoteHost = "sandbox.evernote.com";
	private static final String userStoreUrl = "https://" + evernoteHost
			+ "/edam/user";
	private static final String userAgent = "Evernote/EDAMDemo (Java) "
			+ Constants.EDAM_VERSION_MAJOR + "." + Constants.EDAM_VERSION_MINOR;
	
	private static final String mensagem = "Que bela mensagem temos aqui hein?!";
	

	public static void main(String args[]) throws Exception {
		String newNoteGuid;
		NoteStore.Client noteStore;
		THttpClient userStoreTrans = new THttpClient(userStoreUrl);
		userStoreTrans.setCustomHeader("User-Agent", userAgent);
		TBinaryProtocol userStoreProt = new TBinaryProtocol(userStoreTrans);
		UserStore.Client userStore = new UserStore.Client(userStoreProt,
				userStoreProt);
		boolean versionOk = userStore.checkVersion("Evernote EDAMDemo (Java)",
				com.evernote.edam.userstore.Constants.EDAM_VERSION_MAJOR,
				com.evernote.edam.userstore.Constants.EDAM_VERSION_MINOR);
		if (!versionOk) {
			System.err.println("Incomatible Evernote client protocol version");
			return;
		}
		String notestoreUrl = userStore.getNoteStoreUrl(authToken);
		THttpClient noteStoreTrans = new THttpClient(notestoreUrl);
		noteStoreTrans.setCustomHeader("User-Agent", userAgent);
		TBinaryProtocol noteStoreProt = new TBinaryProtocol(noteStoreTrans);
		noteStore = new NoteStore.Client(noteStoreProt, noteStoreProt);
		// criar nova nota
		Note note = new Note();
		note.setTitle("Testando api do evernote");
		// !! adicionando localização
		addLocalization(note);
		
		// inclusão de uma imagem
		String fileName = "src/enlogo.png";
		String mimeType = "image/png";
		Resource resource = new Resource();
		// imagem
		resource.setData(readFileAsData(fileName));
		// mime type
		resource.setMime(mimeType);
		// nome do arquivo
		ResourceAttributes attributes = new ResourceAttributes();
		attributes.setFileName(fileName);
		resource.setAttributes(attributes);
		// adiciona o resource aos resources da nota
		note.addToResources(resource);
		// To display the Resource as part of the note's content, include an <en-media> tag in the note's ENML content. The en-media tag identifies the
		// corresponding Resource using the MD5 hash.		
		// cria o hash para a imagem
		String hashHex = bytesToHex(resource.getData().getBodyHash());
		// http://dev.evernote.com/documentation/cloud/chapters/ENML.php
		// EML representando a mensagem
		String content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
				+ "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">"
				+ "<en-note>"
				+ "<span style=\"color:green;\">"+mensagem+"</span><br/>"
				+ "<en-media type=\"image/png\" hash=\"" + hashHex + "\"/>"
				+ "</en-note>";
		note.setContent(content);
		// Finally, send the new note to Evernote using the createNote method
		// The new Note object that is returned will contain server-generated
		// attributes such as the new note's unique GUID.
//		Note createdNote = noteStore.createNote(authToken, note);
		Notebook createdNotebook = noteStore.createNotebook(authToken, createNotebook());
		note.setNotebookGuid(createdNotebook.getGuid());
		Note createdNote = noteStore.createNote(authToken, note);
		newNoteGuid = createdNote.getGuid();
		System.out.println("Successfully created a new note with GUID: "
				+ newNoteGuid);		
	}
	
	private static Notebook createNotebook() {
		Notebook notebook = new Notebook();
		notebook.setName("Brincando com notebook");
		return notebook;
	}
	
	private static Data readFileAsData(String fileName) throws Exception {

		// Read the full binary contents of the file
		FileInputStream in = new FileInputStream(fileName);
		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
		byte[] block = new byte[10240];
		int len;
		while ((len = in.read(block)) >= 0) {
			byteOut.write(block, 0, len);
		}
		in.close();
		byte[] body = byteOut.toByteArray();

		// Create a new Data object to contain the file contents
		Data data = new Data();
		data.setSize(body.length);
		data.setBodyHash(MessageDigest.getInstance("MD5").digest(body));
		data.setBody(body);

		return data;
	}
	
	public static String bytesToHex(byte[] bytes) {
		StringBuilder sb = new StringBuilder();
		for (byte hashByte : bytes) {
			int intVal = 0xff & hashByte;
			if (intVal < 0x10) {
				sb.append('0');
			}
			sb.append(Integer.toHexString(intVal));
		}
		return sb.toString();
	}
	private static void addLocalization(Note note) {
		NoteAttributes attr = new NoteAttributes();
		double longitude = -41.4170;
		attr.setLongitude(longitude);
		double latitude = -3.3170;
		attr.setLatitude(latitude);
		note.setAttributes(attr);
	}
}
